#!/bin/bash -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR"
source "$DIR/environment/util.sh"

DISTRO=$(operating_system)
ARCHITECTURE=$(architecture)

function print_help () {
    echo "Usage: $0 [OPTION]"
    echo -e "Check for missing packages and setup the project.\n"
    echo "Optional arguments:"
    echo -e "  -h\tdisplay this help and exit"
    echo -e "  --without-libs-setup\tskip the step for setting up libs"
    echo -e "  --ci\tscript is being run inside ci"
    echo -e "  --offline\tscript is being run offline"
    echo -e "  \t\t(NOTE: this will still try to install dependencies from the internet if the dependency cache is not present)"
}


setup_libs=true
ci=false
check_system_packages=true
if [[ $# -eq 1 && "$1" == "-h" ]]; then
    print_help
    exit 0
else
    while(($#)); do
        case "$1" in
          --without-libs-setup)
              shift
              setup_libs=false
          ;;
          --ci)
              shift
              ci=true
          ;;
          --skip-package-check)
            shift
            check_system_packages=false
          ;;
          --offline)
            ci=true
            check_system_packages=false
            shift
          ;;
          *)
              # unknown option
              echo "Invalid argument provided: $1"
              print_help
              exit 1
          ;;
        esac
    done
fi

if [[ "$check_system_packages" == "true" ]]; then
  if [ "${ARCHITECTURE}" = "arm64" ] || [ "${ARCHITECTURE}" = "aarch64" ]; then
    OS_SCRIPT=$DIR/environment/os/$DISTRO-arm.sh
  else
    OS_SCRIPT=$DIR/environment/os/$DISTRO.sh
  fi
  echo "ALL BUILD PACKAGES: $($OS_SCRIPT list MEMGRAPH_BUILD_DEPS)"
  $OS_SCRIPT check MEMGRAPH_BUILD_DEPS
  echo "All packages are in-place..."
else
  echo "Skipping package checks, good luck!"
fi

# create a default build directory
mkdir -p ./build


if [[ "$setup_libs" == "true" ]]; then
  # Setup libs (download).
  cd libs
  ./cleanup.sh
  ./setup.sh
  cd ..
fi



echo "Done installing dependencies for Memgraph"

echo "Linking git hooks OR skip if .git folder is not there"
if [ -d "$DIR/.git" ]; then
  for hook in $(find $DIR/.githooks -type f -printf "%f\n"); do
    ln -s -f "$DIR/.githooks/$hook" "$DIR/.git/hooks/$hook"
    echo "Added $hook hook"
  done;
else
  echo "WARNING: .git folder not present, skip adding hooks"
fi

# Install precommit hook except on old operating systems because we don't
# develop on them -> pre-commit hook not required -> we can use latest
# packages.
if [[ "$ci" == "false" ]]; then
  echo "Installing pre-commit hooks"
  export PIP_BREAK_SYSTEM_PACKAGES=1
  python3 -m pip install --upgrade pip
  pip install pre-commit black==23.1.* isort==5.12.*
  python3 -m pre_commit install
fi

# Link `include/mgp.py` with `release/mgp/mgp.py`
ln -v -f include/mgp.py release/mgp/mgp.py
